from utils.check import TableNameCheck
from utils.replace_table_name import replace_table_name
from configparser import ConfigParser

import re  # 正规式工具包

if __name__ == '__main__':
    config = ConfigParser()
    config.read('./master/settings', encoding='utf-8')
    print("请输入需要校验的名称类型（1：表名，2：字段名）：")
    name_type = input().strip('\n')
    if name_type == '1':
        config['name_type']['type'] = '1'
        config.write(open('./master/settings', 'w', encoding='utf-8'))
    elif name_type == '2':
        config['name_type']['type'] = '2'
        config.write(open('./master/settings', 'w', encoding='utf-8'))
    while True:
        print('请输入: (输入exit退出程序)')
        # table_name = input()
        # 利用正规式初步校验：匹配字母(a-zA-Z)、数字(0-9)、下划线_，重复一次或多次+，匹配结尾字符$
        # 过滤器：校验、修改之前利用正规式初步校验：匹配字母(a-zA-Z)、数字(0-9)、下划线_，重复零次或多次*，过滤掉不符合规范的输入
        # 规则：指标名称应当由小写字母、下划线组成，开头和结尾不得为下划线
        table_name_pattern = re.compile(r'[a-z0-9][a-z0-9_]*[a-z0-9]')
        while True:
            table_name = input()
            if table_name_pattern.fullmatch(table_name):  # 对于不合规的输入，直到输对为止
                if table_name == 'exit':
                    exit()
                else:
                    break
            else:
                print("命名存在非法字符，请输入由小写字母、数字、下划线组成的命名，且命名以字母、数字开头和结尾：", end='')
                # table_name = input()

        tool = TableNameCheck(table_name)
        tool.check()
        while not tool.is_correct()['is_correct'] or tool.is_correct()['error_type'] == 3:
            print('当前命名为: ' + table_name)
            if tool.is_correct()['error_type'] == 1:
                print('请输入你想替换的词: ', end='')
                word = input().strip('\n')
                table_name = replace_table_name(table_name, tool.is_correct()['index'], word)
                tool = TableNameCheck(table_name)
                tool.check()
            elif tool.is_correct()['error_type'] == 2:
                print('请输入你想添加的词: ', end='')
                word = input().strip('\n')
                table_name = table_name.strip('_') + '_' + word
                tool = TableNameCheck(table_name)
                tool.check()
            elif tool.is_correct()['error_type'] == 3:
                print('当前命名已符合规范，请选择是否继续输入：(1 是 其余任意字符为否)')
                word = input().strip('\n')
                if word == '1':
                    print('请输入你想添加的词: ', end='')
                    word = input().strip('\n')
                    table_name = table_name.strip('_') + '_' + word
                    tool = TableNameCheck(table_name)
                    tool.check()
                else:
                    break
